var api = require('../config/api.js');
var app = getApp();

var bindPhoneNum = 0;

var LoginShowNum = 0;


var AuthShowNum = 0;

function formatTime(date) {
  console.log(date)

  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()

  str = [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':');
  console.log(str)


  return str;
}


// 时间戳转时分秒
function getformatDate(date) {
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];
  // var date = new Date(number * 1000);
  var date = new Date(number);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));

  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));

  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
};

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的的request
 */
function request(url, data = {}, method = "GET", showErrMsg = true, showLogin = true) {
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      timeout: 60000,
      header: {
        'Content-Type': 'application/json',
        'NanOneChargeComputeToken': wx.getStorageSync('token')
      },
      success: function (res) {

        if (res.statusCode == 200) {

          if (res.data.errno == 501) {
            console.log("showLogin:" + showLogin);
            // 登录相关内容
            if (showLogin == true) {
              showGoLogin();
            }

            reject(res.errmsg);

          } else if (res.data.errno == 760) {
            //绑定手机号
            showBingMobile();
            reject(res.errmsg);

          } else {
            if (res.data.errno != 0) {
              if (showErrMsg == true) {
                showErrorToast(res.data.errmsg);
              }

            }
            resolve(res.data);
          }
        } else {
          reject(res.errmsg);
        }

      },
      fail: function (err) {
        reject(err)
      }
    })
  });
}

function redirect(url) {

  //判断页面是否需要登录
  if (false) {
    wx.redirectTo({
      url: '/pages/auth/login/login'
    });
    return false;
  } else {
    wx.redirectTo({
      url: url
    });
  }
}

function showErrorToast(msg) {
  wx.showToast({
    title: msg,
    icon: 'none' //占用文字位置，去掉，多显示错误文本
  })
}

function showToast(msg) {
  wx.showToast({
    title: msg,
  })
}

function showBingMobile() {
  if (bindPhoneNum <= 0) {
    bindPhoneNum++;
    wx.showModal({
      title: '系统提示',
      confirmColor: '#296DBA',
      content: '需要绑定手机号继续服务？',
      success: function (res) {
        console.log(res)
        bindPhoneNum--;
        if (res.confirm) {
          wx.navigateTo({
            url: `/pagesBusiness/pages/user/userInfo/mobile`
          });
        }
      },
      fail: function () {
        bindPhoneNum--;
      }
    })
  }

}



function showGoLogin() {
  if (LoginShowNum <= 0) {
    LoginShowNum++;
    try {
      wx.removeStorageSync('userInfo');
      wx.removeStorageSync('token');
    } catch (e) {
      // Do something when catch error
    }
    wx.showModal({
      title: '系统提示',
      confirmColor: '#296DBA',
      content: '需要登录继续服务？',
      success: function (res) {
        console.log(res)
        LoginShowNum--;
        if (res.confirm) {
          wx.navigateTo({
            url: `/pages/auth/login/login`
          });
        }
      },
      fail: function () {
        LoginShowNum--;
      }
    })
  }

}


/**
 * 
 * url 解析
 * @param {} url 
 */
function parseUrl(url) {
  console.log("paseUrl");
  try {

    // 分离查询参数部分
    let qIndex = url.indexOf('?');
    console.log(qIndex);
    let base = url;
    let queryString = '';
    if (qIndex !== -1) {
      base = url.substring(0, qIndex);
      queryString = url.substring(qIndex + 1);
    }


    console.log(queryString);

    // 解析查询参数
    const params = {};
    if (queryString) {
      const pairs = queryString.split('&');
      for (const pair of pairs) {
        const [key, value = ''] = pair.split('=').map(decodeURIComponent);

        // 处理重复参数名
        if (params.hasOwnProperty(key)) {
          if (Array.isArray(params[key])) {
            params[key].push(value);
          } else {
            params[key] = [params[key], value];
          }
        } else {
          params[key] = value;
        }
      }
    }

    // 构建基础URL（保留哈希部分）
    const baseUrl = base;

    return {
      baseUrl: baseUrl,
      params: params
    };

  } catch (error) {
    console.error(error);
  }

}

function parseWebViewUrl(url) {
  let map = parseUrl(url);
  let strParams = JSON.stringify(map.params);
  wx.navigateTo({
    url: `/pages/webview/index?url=${map.baseUrl}&params=${strParams}`,
  })

}





module.exports = {
  getformatDate,
  formatTime,
  request,
  redirect,
  showToast,
  showErrorToast,
  parseUrl,
  parseWebViewUrl,
}